package edu.sandau.basic.service.impl;

import edu.sandau.basic.domain.Role;
import edu.sandau.basic.mapper.RoleMapper;
import edu.sandau.basic.service.RoleService;
import edu.sandau.basic.vo.BasicMsg;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;

import java.util.Date;
import java.util.List;

@Service
public class RoleServiceImpl implements RoleService {

    @Resource
    private RoleMapper roleMapper;

    @Override
    public List<Role> listAll() {
        return roleMapper.selectAll();
    }

    @Override
    public Role getById(Integer id) {
        return roleMapper.selectByPrimaryKey(id);
    }

    @Override
    public BasicMsg addRole(Role role) {

        role.setId(null);
        role.setCreatetime(new Date());
        role.setUpdatetime(new Date());
        role.setCreateperson(1);
        role.setUpdateperson(1);
        int rows = roleMapper.insert(role);
        return rows == 1 ? BasicMsg.ok("角色创建成功") : BasicMsg.error("创建失败");
    }

    @Override
    public BasicMsg updateRole(Integer id, Role role) {
        role.setId(id);
        role.setUpdatetime(new Date());
        role.setUpdateperson(1);
        int rows = roleMapper.updateByPrimaryKeySelective(role);
        return rows == 1 ? BasicMsg.ok("更新成功") : BasicMsg.error("更新失败");
    }

    @Override
    public BasicMsg patchRole(Integer id, Role role) {
        Role db = roleMapper.selectByPrimaryKey(id);
        if (db == null) return BasicMsg.error("角色不存在");

        if (role.getRolecode() != null) db.setRolecode(role.getRolecode());
        if (role.getIsActive() != null) db.setIsActive(role.getIsActive());

        db.setUpdatetime(new Date());
        db.setUpdateperson(1);

        int rows = roleMapper.updateByPrimaryKeySelective(db);
        return rows == 1 ? BasicMsg.ok("部分更新成功") : BasicMsg.error("更新失败");
    }

    @Override
    public BasicMsg deleteRole(Integer id) {
        int rows = roleMapper.deleteByPrimaryKey(id);
        return rows == 1 ? BasicMsg.ok("删除成功") : BasicMsg.error("删除失败");
    }

    @Override
    public List<Role> listActive() {
        return roleMapper.selectActiveRoles();
    }
}
